# 平衡二叉树

# Definition for a binary tree node.
class TreeNode(object):
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


class Solution(object):
    def isBalanced(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        return self.height(root) >= 0

    def height(self, root):
        if not root:
            return 0

        leftTree = self.height(root.left)
        rightTree = self.height(root.right)

        # -1 代表有子树不是二叉树
        if leftTree == -1 or rightTree == -1 or abs(leftTree - rightTree) > 1:
            return -1
        else:
            return 1 + max(leftTree, rightTree)
